package com.learn.mq.util;

import com.alibaba.fastjson2.JSON;
import com.learn.mq.param.Message;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * ClassName:RocketMQMessageSender
 * Package:com.learn.mq.util
 * Description:
 *
 * @Author:@郭先森
 * @Create:2025/7/30 - 18:25
 * @Version:v1.0
 */
@Slf4j
@Component
public class RocketMQMessageSender {

    @Autowired
    @Qualifier("defaultRocketMQTemplate")
    private RocketMQTemplate defaultRocketMQTemplate;

    @Autowired
    @Qualifier("transactionRocketMQTemplate")
    private RocketMQTemplate transactionRocketMQTemplate;

    public  boolean sendMsg(String topic, String tag, Message message){
        String msg = JSON.toJSONString(message);
        org.springframework.messaging.Message<String> springMsg =
                MessageBuilder.withPayload(msg)
                        .setHeader("KEYS", message.getMsgId()) // 必须设置KEYS用于消息追踪
                        .build();
        log.info("将自己的消息封装转换为官方的格式之后的样子："+springMsg);
        defaultRocketMQTemplate.send(topic + ":" + tag, springMsg);
        return true;
    }

}
